package com.health.mapp.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.health.db.model.RegisterOrder;
import com.health.db.model.RegisterOrderExample;
import com.health.db.model.UserCardList;
import com.health.db.model.UserCardListExt;
import com.health.db.service.order.IRegisterOrderService;
import com.health.db.service.user.IUserCardListService;
import com.health.db.service.user.IUserLISTService;
import com.health.mapp.bean.Header;
import com.health.mapp.bean.PayControllerDocReq;
import com.health.mapp.bean.PayControllerDocResp;
import com.health.mapp.utils.Constant;
import com.health.mapp.utils.DateUtils;
import com.health.mapp.utils.Response;
import com.health.mapp.utils.ResultCode;

/**医生扣款接口
 * @pramati
 * 	private Long  orderId; //订单号
 *  private int type;//0:钱包支付,1:服务卡支付
 *  钱包支付：
 *  
 *  卡支付：
 *  
 *
 */
public class PayControllerDocImpl implements ActionInterface {
	
	//service import
	private IRegisterOrderService registerOrderService  ;
	private IUserLISTService userLISTService;
	private IUserCardListService userCardListService;
	
	@Override
	public Response execute(Header header, Object reqBean) throws Exception {
		
		PayControllerDocReq req = (PayControllerDocReq) reqBean; 
		PayControllerDocResp _resp = new PayControllerDocResp();
		String orderId = req.getOrderId();
		//支付方式 4 ,5 ,2
		String type = req.getCardType();
		
		//0 card 1 cash
		String payType =req.getPayType();	
		//1 扣 2退
		String operType = req.getType();
		
		Long userId = req.getUserId();
		
		String times =req.getTimes();
		
		if (StringUtils.isBlank(type)) {
			type="2";
		}
		
		if (StringUtils.isBlank(payType)) {
			payType="1";
		}
		
		
		if (StringUtils.isBlank(times)) {
			times = "1";
		}
		
		if ("2".equals(operType)){
			_resp.setErrorCode(ResultCode.OPERATION_ORDER_ERROR_3016);
			_resp.setErrorMsg(ResultCode.OPERATION_ORDER_ERROR_3016_NOTE);
			return _resp;
		}
		
		
		if (StringUtils.isBlank(orderId) ) {
			_resp.setErrorCode(ResultCode.OPERATION_LAKE_PARAMETER_ORDERID);
			_resp.setErrorMsg(ResultCode.OPERATION_LAKE_PARAMETER_ORDERID_NOTE);
			return _resp;
		}else if(userId==0) {
			_resp.setErrorCode(ResultCode.OPERATION_LAKE_PARAMETER_USERID);
			_resp.setErrorMsg(ResultCode.OPERATION_LAKE_PARAMETER_USERID_NOTE);
			return _resp;
		}
		 
		else
		{
			
			//获取当前要支付的订单
			RegisterOrder  currRegisterOrder =registerOrderService.selectSimpleSingleByOrderId(Long.valueOf(orderId));
			
			currRegisterOrder.setRegisterid(Long.valueOf(orderId));
			
			//判断订单状态 订单不存在或者是免费订单，或是订单状态不是等待支付
			if (currRegisterOrder.getRegistertypeid().intValue()!=Constant.CONSTANTS_ORDER_TYPE_ID_4.intValue()) {
				_resp.setErrorCode(ResultCode.OPERATION_ORDER_ERROR_3026);
				_resp.setErrorMsg(ResultCode.OPERATION_ORDER_ERROR_3026_NOTE);
				return _resp;
			}
			else
			{
				if ("2".equals(operType)) {
					
					String cardItemID = currRegisterOrder.getCardItemID();
					
					if (StringUtils.isBlank(cardItemID)) {
						
						_resp.setErrorCode(ResultCode.OPERATION_ORDER_ERROR_3001);
						_resp.setErrorMsg(ResultCode.OPERATION_ORDER_ERROR_3001_NOTE);
						return _resp;
					}else{
						
						String[] cardItemIDs=cardItemID.split(",");
						String[] cardIds=currRegisterOrder.getCardID().split(",");
						String[] cardJournalAmounts=currRegisterOrder.getCardJournalAmount().split(",");
						
						int index = -1;
						
						//查看扣减任意一次卡的卡号
						for (int i = 0; i < cardItemIDs.length; i++) {
							String temp = cardItemIDs[i].replace("T", "");
							
							if (temp.equals(type)) {
								
								index = i;
								break;
							}
						}
						
						if (index>=0) {
							
							UserCardList  userCardList =userCardListService.selectByCardId(Long.valueOf(cardIds[index]));
							
							if(null!=userCardList){
								
								//数据过滤
								String newcardItemID= cardItemID.replaceFirst("T"+type, "").replace(",,", ",");
								String newCardID =currRegisterOrder.getCardID().replaceFirst(cardIds[index], "").replace(",,", ",");
								String newCardJournalAmount= currRegisterOrder.getCardJournalAmount().replaceFirst(cardJournalAmounts[index], "").replace(",,", ",");
								
								//起始
								if (newcardItemID.startsWith(",")) {
									newcardItemID=newcardItemID.replaceFirst(",", "");
								}
								if (newCardID.startsWith(",")) {
									newCardID=newCardID.replaceFirst(",", "");
								}
								if (newCardJournalAmount.startsWith(",")) {
									newCardJournalAmount=newCardJournalAmount.replaceFirst(",", "");
								}
								
								//结束
								if (newcardItemID.endsWith(",")) {
									newcardItemID=newcardItemID.replace(",", "");
									
									newcardItemID = newcardItemID.substring(0,newcardItemID.length()-1);
									
								}
								if (newCardID.endsWith(",")) {
									
									newCardID = newCardID.substring(0,newCardID.length()-1);
								}
								if (newCardJournalAmount.endsWith(",")) {
									
									newCardJournalAmount = newCardJournalAmount.substring(0,newCardJournalAmount.length()-1);
								}
								if (("4".equals(type))) 
								{
									userCardList.setLefttime04(userCardList.getLefttime04().add(new BigDecimal(1)));
								}
								else if (("5".equals(type))) 
								{
									userCardList.setLefttime05(userCardList.getLefttime05().add(new BigDecimal(1)));
								}
								
								currRegisterOrder.setCardID(newCardID);
								currRegisterOrder.setCardItemID(newcardItemID);
								currRegisterOrder.setCardJournalAmount(newCardJournalAmount);
								
								registerOrderService.updateOrder4CardRefoundDoc(currRegisterOrder, userCardList,type);
								}else{
									//信息错误
									_resp.setErrorCode(ResultCode.OPERATION_ORDER_ERROR_3001);
									_resp.setErrorMsg(ResultCode.OPERATION_ORDER_ERROR_3001_NOTE);
									return _resp;
								}
							
						}else{
							//信息错误
							_resp.setErrorCode(ResultCode.OPERATION_ORDER_ERROR_3001);
							_resp.setErrorMsg(ResultCode.OPERATION_ORDER_ERROR_3001_NOTE);
							return _resp;
						}
						
					}
					
				
					
					
					
				}else{
					//查询到用户可用的卡列表，并返回离失效时间最近的一张卡
					UserCardListExt queryUserCardListExt =new UserCardListExt();
					queryUserCardListExt.setOwnerid(userId);
					
					
					//服务卡支付（或者叫什么其他的卡） -2 额度不足
					int flag= -1;
				
					if(StringUtils.isNotBlank(payType)&&("1").equals(payType)){
						queryUserCardListExt.setLefttime02(new BigDecimal(times));
						
						List<UserCardList> list =userCardListService.selectUserCardLists(queryUserCardListExt);
						
						currRegisterOrder.setRegisterTotal(new BigDecimal(times));
						if(null==list||list.size()==0 )
						{
							flag =-2;
							//flag= walletPayment(currRegisterOrder,times ,type);
						}else{
							flag= walletPayment(currRegisterOrder ,list,type);
						}
						
					}else{
						//增加剩余时间（次数，余额）校验，如果余额已为0 ，或是余额不够此次消费，则不返回
						if (("4".equals(type))) 
						{
							queryUserCardListExt.setLefttime04(new BigDecimal(1));
						}
						else if (("5".equals(type))) 
						{
							// OrderBillTime未写入registe_order表
							queryUserCardListExt.setLefttime05(new BigDecimal(1));
						}
						
						List<UserCardList> list =userCardListService.selectUserCardLists(queryUserCardListExt);
						
						if(null==list||list.size()==0 )
						{
							_resp.setErrorCode(ResultCode.OPERATION_CARD_PAYMENT_NOT_ENOUGH_ERROR);
							_resp.setErrorMsg(ResultCode.OPERATION_CARD_PAYMENT_NOT_ENOUGH_ERROR_NOTE);
							return _resp;
						}
						flag= serviceCardPayment( userId, currRegisterOrder ,list,type);
					}
					
					
					
					//总额度不足，提示使用其他支付方式。
					if (flag==Constant.CARD_PAYMENT_NOT_ENOUGH) {
						_resp.setErrorCode(ResultCode.OPERATION_CARD_PAYMENT_NOT_ENOUGH_ERROR);
						_resp.setErrorMsg(ResultCode.OPERATION_CARD_PAYMENT_NOT_ENOUGH_ERROR_NOTE);
						return _resp;
					}
				}
			}
		}
		
		_resp.setErrorCode(ResultCode.OPERATION_SUCCESS);
		_resp.setErrorMsg(ResultCode.OPERATION_SUCCESS_NOTE);
 
		return _resp;
	}

	
	
	
	public int serviceCardPayment(long userId,RegisterOrder  currRegisterOrder, List<UserCardList>  userCardList,String type )
	{
		    long  orderId=currRegisterOrder.getRegisterid();
		    
		    //准备入库的数据对象
		    RegisterOrder orderInfo = new RegisterOrder();
		    //返回对象
		    RegisterOrderExample registerOrderExample = new RegisterOrderExample();
			orderInfo.setRegisterid(orderId);
            Date currDateTime=DateUtils.getDatetime();
			orderInfo.setUpdateDate(currDateTime);
			
			UserCardList userCard =userCardList.get(0);
			
			String cardItemID = currRegisterOrder.getCardItemID();
			if (Constant.PAYMENT_SERVICE_CARD_4.equals(type)) 
			{
				BigDecimal leftTime= userCard.getLefttime04();
				userCard.setLefttime04(leftTime.subtract(new BigDecimal(1)));
				if (StringUtils.isBlank(cardItemID)) {
					orderInfo.setCardItemID("T"+String.valueOf(userCardList.get(0).getCardid()));
				}else{
					orderInfo.setCardItemID(cardItemID+","+"T"+Constant.PAYMENT_SERVICE_CARD_4);
				}
			}
			else if (Constant.PAYMENT_SERVICE_CARD_5.equals(type)) 
			{
				// OrderBillTime未写入registe_order表
				BigDecimal leftTime= userCard.getLefttime05();
				userCard.setLefttime05(leftTime.subtract(new BigDecimal(1)));
				if (StringUtils.isBlank(cardItemID)) {
					orderInfo.setCardItemID("T"+Constant.PAYMENT_SERVICE_CARD_5);
				}else{
					orderInfo.setCardItemID(cardItemID+","+"T"+Constant.PAYMENT_SERVICE_CARD_5);
				}
			}
	
			String cardJournalAmount = currRegisterOrder.getCardJournalAmount();
			String cardID =currRegisterOrder.getCardID();
			
			if (StringUtils.isBlank(cardJournalAmount)) {
				orderInfo.setCardJournalAmount("1");
			}else{
				orderInfo.setCardJournalAmount(cardJournalAmount+","+"1");
			}
			
			if (StringUtils.isBlank(cardID)) {
				orderInfo.setCardID(String.valueOf(userCardList.get(0).getCardid()));
			}else{
				orderInfo.setCardID(cardID+","+String.valueOf(userCardList.get(0).getCardid()));
			}
			
			//更新 金额 和日期 ,卡号为条件
			userCard.setUpdateDate(DateUtils.now());
			userCard.setCardid(userCard.getCardid());
			registerOrderExample = registerOrderService.updateOrder4CardPaymentDoc(orderInfo, userCard,type);
			
			return  registerOrderExample.getUpdateNum();
	}
	
	/**
	 * 用户有激活卡，激活卡有实效
	 * @param currRegisterOrder
	 * @param userCardList
	 * @param commont 4 5
	 * @return
	 */
	public int walletPayment(RegisterOrder  currRegisterOrder, List<UserCardList>  userCardList,String commont )
	{

	    long  orderId=currRegisterOrder.getRegisterid();
	    
	    //准备入库的数据对象
	    RegisterOrder orderInfo = new RegisterOrder();
	    //返回对象
	    RegisterOrderExample registerOrderExample = new RegisterOrderExample();
		orderInfo.setRegisterid(orderId);
		orderInfo.setUserid(currRegisterOrder.getUserid());
		
		orderInfo.setUpdateDate(new Date());
		
		//String 初始化
		orderInfo.setCardJournalAmount(null==currRegisterOrder.getCardJournalAmount()?"":currRegisterOrder.getCardJournalAmount()+",");
		orderInfo.setCardID(null==currRegisterOrder.getCardID()?"":currRegisterOrder.getCardID()+",");
		orderInfo.setCardItemID(null==currRegisterOrder.getCardItemID()?"":currRegisterOrder.getCardItemID()+",");
		orderInfo.setRegistertypeid(currRegisterOrder.getRegistertypeid());
		//orderInfo.setRegisterTotal(currRegisterOrder.getRegisterTotal())
		
		//现在只是支付，所以订单剩余时间也是订单的总时间
		orderInfo.setOrderLeftTime(currRegisterOrder.getOrderBillTime());
		List<UserCardList>  userCardListForUpdate = new ArrayList<UserCardList>();
		
		BigDecimal leftTime02=new BigDecimal(0);
		BigDecimal consTime=currRegisterOrder.getRegisterTotal();
		
		BigDecimal total=new BigDecimal(0);
		for (int i = 0; i < userCardList.size(); i++) {
			UserCardList userCard =userCardList.get(i);
			BigDecimal cardLeftTime = userCard.getLefttime02();
			total= total.add(cardLeftTime);
			if (cardLeftTime.compareTo(new BigDecimal(0))<=0) {
				continue;
			}
			leftTime02 =cardLeftTime.subtract(consTime);
			
			if (leftTime02.compareTo(new BigDecimal(0))>=0) {
				//更新 金额 和日期 ,卡号为条件
				userCard.setLefttime02(leftTime02);
				userCard.setUpdateDate(DateUtils.now());
				userCard.setCardid(userCard.getCardid());
				userCard.setTemp(consTime);
				userCardListForUpdate.add(userCard);
				orderInfo.setCardJournalAmount(orderInfo.getCardJournalAmount()+  String.valueOf(consTime.setScale(2,  BigDecimal.ROUND_HALF_UP)));
				orderInfo.setCardID(orderInfo.getCardID()+userCard.getCardid());
				orderInfo.setCardItemID(orderInfo.getCardItemID()+"T"+Constant.PAYMENT_SERVICE_CARD_2);
				
				break;
			}else{
				
				//更新 金额 和日期 ,卡号为条件
				userCard.setTemp(userCard.getLefttime02());
				userCard.setLefttime02(new BigDecimal(0));
				userCard.setUpdateDate(DateUtils.now());
				userCard.setCardid(userCard.getCardid());
				userCardListForUpdate.add(userCard);
				
				orderInfo.setCardJournalAmount(orderInfo.getCardJournalAmount()+ String.valueOf(cardLeftTime.setScale(2,  BigDecimal.ROUND_HALF_UP)) +",");
				orderInfo.setCardID(orderInfo.getCardID()+userCard.getCardid()+",");
				orderInfo.setCardItemID(orderInfo.getCardItemID()+"T"+Constant.PAYMENT_SERVICE_CARD_2+",");
				
				consTime = new BigDecimal( Math.abs(leftTime02.doubleValue()));
			}
				
		}
		
		//多条数据卡支付不足的时候会已","结尾 删除","
		if (orderInfo.getCardJournalAmount().endsWith(",")) {
			orderInfo.setCardJournalAmount(orderInfo.getCardJournalAmount().substring(0, orderInfo.getCardJournalAmount().length()-1));
			orderInfo.setCardID(orderInfo.getCardID().substring(0,orderInfo.getCardID().length()-1));
			orderInfo.setCardItemID(orderInfo.getCardItemID().substring(0,orderInfo.getCardItemID().length()-1));
		}
		if (total.compareTo(currRegisterOrder.getRegisterTotal()) < 0) {

			return -2;
			/*//卡额度不够需要用余额来补充
			orderInfo.setCardJournalAmount(orderInfo.getCardJournalAmount() +","+String.valueOf(currRegisterOrder.getRegisterTotal().subtract(total).setScale(2,  BigDecimal.ROUND_HALF_UP)) );
			orderInfo.setCardID(orderInfo.getCardID()+",0");
			orderInfo.setCardItemID(orderInfo.getCardItemID()+",P");
			// 多条选择批处理
			if (userCardListForUpdate.size() == 1) {
				
				registerOrderExample = registerOrderService.updateOrder4WalletAndCardPaymentDoc(orderInfo,
								userCardListForUpdate.get(0),Constant.PAYMENT_SERVICE_CARD_2,
								currRegisterOrder.getRegisterTotal().subtract(total));
			} else {
				
				registerOrderExample = registerOrderService.updateOrder4WalletAndCardPaymentDoc(orderInfo,
								userCardListForUpdate,Constant.PAYMENT_SERVICE_CARD_2,
								currRegisterOrder.getRegisterTotal().subtract(total));
			}*/

		} else {
			// 多条选择批处理
			if (userCardListForUpdate.size() == 1) {
				
				registerOrderExample = registerOrderService.updateOrder4CardPaymentDoc(orderInfo,
								userCardListForUpdate.get(0),Constant.PAYMENT_SERVICE_CARD_2);
			} else {
				registerOrderExample = registerOrderService.updateOrder4CardPaymentDoc(orderInfo,
								userCardListForUpdate,Constant.PAYMENT_SERVICE_CARD_2);
			}
		}
		
		
		return  registerOrderExample.getUpdateNum();
	}
	
	
	/**
	 * 纯余额支付
	 * @param currRegisterOrder
	 * @param times 扣款金额
	 * @param commont 4 5 
	 * @return
	 */
	public int walletPayment(RegisterOrder  currRegisterOrder,String times,String commont)
	{

	    long  orderId=currRegisterOrder.getRegisterid();
	    
	    //准备入库的数据对象
	    RegisterOrder orderInfo = new RegisterOrder();
	    //返回对象
	    RegisterOrderExample registerOrderExample = new RegisterOrderExample();
		orderInfo.setRegisterid(orderId);
		orderInfo.setUserid(currRegisterOrder.getUserid());
		
		orderInfo.setUpdateDate(new Date());
		orderInfo.setRegisterDate(currRegisterOrder.getRegisterDate());	
		orderInfo.setRegistertypeid(currRegisterOrder.getRegistertypeid());
		
		orderInfo.setCardJournalAmount(null==currRegisterOrder.getCardJournalAmount()?times:currRegisterOrder.getCardJournalAmount()+","+times);
		orderInfo.setCardID(null==currRegisterOrder.getCardID()?"0":currRegisterOrder.getCardID()+",0");
		orderInfo.setCardItemID(null==currRegisterOrder.getCardItemID()?"P":currRegisterOrder.getCardItemID()+",P");
		
		registerOrderExample=registerOrderService.updateOrder4WalletPaymentDoc(orderInfo,times);
		
		return  registerOrderExample.getUpdateNum();
	}
	
	
	public IRegisterOrderService getRegisterOrderService() {
		return registerOrderService;
	}

	public void setRegisterOrderService(IRegisterOrderService registerOrderService) {
		this.registerOrderService = registerOrderService;
	}

	/**
	 * @return the userLISTService
	 */
	public IUserLISTService getUserLISTService() {
		return userLISTService;
	}

	/**
	 * @param userLISTService the userLISTService to set
	 */
	public void setUserLISTService(IUserLISTService userLISTService) {
		this.userLISTService = userLISTService;
	}

	/**
	 * @return the userCardListService
	 */
	public IUserCardListService getUserCardListService() {
		return userCardListService;
	}

	/**
	 * @param userCardListService the userCardListService to set
	 */
	public void setUserCardListService(IUserCardListService userCardListService) {
		this.userCardListService = userCardListService;
	}
	
	


}
